
import 'dart:io';

import 'package:fluent_ui/fluent_ui.dart' as fui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:syria_sports/core/network/internet_cubit.dart';
import 'package:syria_sports/page_config.dart';
import 'package:syria_sports/presentation/dashboard_container_screen/dashboard_container_screen.dart';
import 'package:syria_sports/presentation/my_qr_code/bloc/my_qr_code_screen.dart';
import 'package:syria_sports/presentation/public_home_page/bloc/public_home_screen.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:syria_sports/web_page.dart';
import 'core/app_export.dart';
import 'data/remote/dio_helper.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:flutter/foundation.dart';

Future<void> deleteDatabase() async =>
    databaseFactory.deleteDatabase(await getDatabasesPath());
late PackageInfo packageInfo;

/// Checks if the current environment is a desktop environment.
bool get isDesktop {
  if (kIsWeb) return false;
  return [
    TargetPlatform.windows,
    TargetPlatform.linux,
    TargetPlatform.macOS,
  ].contains(defaultTargetPlatform);
}

var globalMessengerKey = GlobalKey<ScaffoldMessengerState>();

void main() async {
  loadPageConfig().then((value) {
    if (value.isEnable) {
      runApp(WebPage(pageData: value));
    } else {
      startApp();
      runApp(const MyApp());
    }
  });
}

void startApp() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  if(!kIsWeb) {
    FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
    if (Platform.isWindows || Platform.isLinux) {
      // Initialize FFI
      sqfliteFfiInit();
      databaseFactory = databaseFactoryFfi;
    }
  }
  //deleteDatabase();
  List results = await Future.wait([
    //if(!kIsWeb)
    PackageInfo.fromPlatform(),
    PrefUtils.init(),
    initializeDateFormatting(),
  ]);

  if(!kIsWeb) {
    packageInfo = results.first;
    AppConstant.appName = packageInfo.appName;
    AppConstant.packageName = packageInfo.packageName;
    AppConstant.version = packageInfo.version;
    AppConstant.buildNumber = packageInfo.buildNumber;
    FlutterNativeSplash.remove();
  }
  DioHelper.init();
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<ThemeBloc>(
          create: (context) => ThemeBloc(
            ThemeState(
              themeType:PrefUtils.getThemeData(),
            ),
          ),
        ),
        BlocProvider<InternetCubit>(
          create: (context) => InternetCubit(Connectivity()),
        ),
      ],
      child: BlocBuilder<ThemeBloc, ThemeState>(
        builder: (context, state) {
          return MaterialApp(
            theme: theme,
            darkTheme: themeDark,
            title: 'Syria Sports',
            navigatorKey: NavigatorService.navigatorKey,
            debugShowCheckedModeBanner: false,
            locale:const Locale(
              'ar',
            ),
            localizationsDelegates: const [
              AppLocalizationDelegate(),
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('en'),
              Locale('ar'),
            ],
            home: BlocListener<InternetCubit, InternetState>(
              listener: (context, state) {},
              child: PrefUtils.isCoach()
                  ? DashboardContainerScreen.builder(context)
                  : ((PrefUtils.isLogged() && PrefUtils.isQRQuickAccessEnabled())
                  ? MyQrCodeScreen(
                code: PrefUtils.getBarcode(),
                isFirstScreen: true,
              )
                  : const PublicHomeScreen()),
            ),
          );
        },
      ),
    );
  }
}

